/**
 * @author hoang.pt
 * @version $Id$
 */

package test1.problem1;

import java.io.*;
import java.util.*;
import java.util.regex.*;

/**
 * Fan Manager
 * @author hoang.pt
 */
public class FanManager {

    InputStreamReader reader = new InputStreamReader(System.in);
    BufferedReader in = new BufferedReader(reader);

    /**
     * @var Fan, universal variable
     */
    Fan fan;
    
    /**
     * @var ArrayList, for store list, can move to view
     */
    ArrayList<Fan> list;

    /**
     * input data
     * @author hoang.pt
     * @throws IOException
     */
    void inputData() throws IOException {

        //input 1
        System.out.println("Information fan");
        System.out.println("model: ");
        String model = in.readLine();

        System.out.println("power");
        double power = Double.parseDouble(in.readLine());

        System.out.println("remote control");
        boolean remotecontrol = Boolean.parseBoolean(in.readLine());

        fan = new Fan(model, power, remotecontrol);
    }

    /**
     * save to file
     * @author hoang.pt
     * @throws IOException
     */
    void saveToFile() throws IOException {

        //save to list
        list = new ArrayList<Fan>();

        //loop
        for (int i=0; i<2; i++) {
            inputData();
            list.add(fan);
        }

        //check list
        for (Fan fan : list) {
            System.out.print(fan.getModel() + " ");
        }
        System.out.print("\n");

        //save list to file
        FileOutputStream f = new FileOutputStream("fan.dat");
        ObjectOutputStream writer = new ObjectOutputStream(f);

        writer.writeObject(list);

        writer.flush();
        writer.close();
        f.close();
    }

    /**
     * read from file
     * @author hoang.pt
     * @throws FileNotFoundException
     * @throws IOException
     * @throws ClassNotFoundException
     */
    void readFromFile() throws FileNotFoundException, IOException, ClassNotFoundException {
        
        FileInputStream f = new FileInputStream("fan.dat");
        ObjectInputStream reader = new ObjectInputStream(f);

        Object list = reader.readObject();
        ArrayList<Fan> fanList = (ArrayList<Fan>) list;

        for (Fan fan : fanList) {
            System.out.println(fan);
        }
    }

    /**
     * search fan
     * @author hoang.pt
     * @throws IOException
     */
    void searchFan() throws IOException {
        
        System.out.println("Enter model: ");
        String pattern = in.readLine();
        Pattern ptnObj = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);

        //search fan1, loop fan 2
        for (Fan fan : list) {
            String text = fan.getModel();
            Matcher matcher = ptnObj.matcher(text);

            while (matcher.find()) {
                System.out.println("Found");
                System.out.println(fan);
            }
        }
        
    }
}
